import { useEffect, useState } from 'react'

import { queryUserPcsListApi } from '@/api/sys/organization'
import AekModal, { PromiseThen } from '@/components/AekModal'
import AekTable from '@/components/AekTable'
import SearchForm from '@/components/SearchForm'
import { defaultPageSize, getPagination, getRowSelection, message } from '@/utils/antdHelper'
import { requestWithTry } from '@/utils/request'

const WorkerModal = () => {
  const [loading, setLoading] = useState(false)
  const [content, setContent] = useState([])
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: defaultPageSize,
    total: 0,
  })
  const [searchParams, setSearchParams] = useState({})

  const [selectedRow, setSelectedRow] = useState([])

  const getPageList = async (props = {}) => {
    setLoading(true)
    const { data } = await requestWithTry(queryUserPcsListApi, { ...searchParams, ...pagination, ...props })
    const { content, total } = data || {}
    if (total !== pagination.total) {
      setPagination({ ...pagination, total })
    }
    setLoading(false)
    setContent(content)
  }

  useEffect(() => {
    getPageList()
  }, [searchParams, pagination])

  const searchProps = {
    searchParams,
    formData: [
      {
        field: 'fullName',
        label: '姓名',
        component: {
          name: 'Input',
        },
      },
      {
        field: 'mobileNumber',
        label: '手机号',
        component: {
          name: 'Input',
        },
      },
    ],
    onSearch: values => {
      const state = {
        ...pagination,
        current: 1,
        ...values,
      }
      setSearchParams(values)
      getPageList(state)
    },
  }

  /** @type {import("@/components/AekTable").AekTableProps} */
  const tableProps = {
    configKey: 'pcsNursingWorkers-WorkerModal',
    showConfig: false,
    rowKey: 'id',
    loading,
    dataSource: content,
    pagination: getPagination(pagination, (current, pageSize) => {
      setPagination({ ...pagination, current, pageSize })
      getPageList({ current, pageSize })
    }),
    beforePagination: selectedRow.length > 0 ? `当前选择：${selectedRow[0].fullName}` : null,
    columns: [
      { dataIndex: 'fullName', title: '姓名' },
      { dataIndex: 'userName', title: '用户名' },
      { dataIndex: 'mobileNumber', title: '手机号' },
      { dataIndex: 'obNumber', title: '工号' },
      { dataIndex: 'departmentName', title: '组织架构' },
      { dataIndex: 'roleNames', title: '角色' },
    ],
    rowSelection: getRowSelection({ type: 'radio', selList: selectedRow, setSelList: setSelectedRow }),
  }

  const onOk = async () => {
    if (!selectedRow) {
      return message.error('请选择护工')
    }
    return selectedRow
  }

  return (
    <AekModal title='选择护工' width={1000} onOk={onOk}>
      <SearchForm {...searchProps} />
      <div className='h-400px flex flex-col'>
        <AekTable {...tableProps} />
      </div>
    </AekModal>
  )
}

WorkerModal.PromiseThen = PromiseThen

export default WorkerModal
